package personal.jinhui.paprika.ui;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.io.File;
import java.io.InputStream;
import java.io.IOException;
import org.jivesoftware.smack.util.StringUtils;

import personal.jinhui.paprika.PaprikaApplication;
import personal.jinhui.paprika.providers.AvatarProvider;
import personal.jinhui.paprika.service.Contact;
import personal.jinhui.paprika.service.PresenceAdapter;
import personal.jinhui.paprika.service.UserInfo;
import personal.jinhui.paprika.ui.dialogs.builders.Alias;
import personal.jinhui.paprika.ui.dialogs.builders.DeleteContact;
import personal.jinhui.paprika.ui.dialogs.builders.ResendSubscription;
import personal.jinhui.paprika.utils.ImageHelper;
import personal.jinhui.paprika.utils.PaprikaBroadcastReceiver;
import personal.jinhui.paprika.utils.SortedList;
import personal.jinhui.paprika.utils.Status;

import android.app.Activity;
import android.app.Dialog;
import android.app.LocalActivityManager;
import android.app.SearchManager;
import android.app.TabActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.os.Parcelable;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;

import personal.jinhui.paprika.R;
import personal.jinhui.paprika.service.aidl.IPaprikaRosterListener;
import personal.jinhui.paprika.service.aidl.IChatManager;
import personal.jinhui.paprika.service.aidl.IRoster;
import personal.jinhui.paprika.service.aidl.IXmppFacade;

/**
 * The contact list activity displays the roster of the user.
 */
public class HomeActivity extends TabActivity {
	private static final String TAG = "HomeActivity";

	private static final Intent SERVICE_INTENT = new Intent();
	static {
		SERVICE_INTENT.setComponent(new ComponentName(
				"personal.jinhui.paprika",
				"personal.jinhui.paprika.PaprikaService"));
	}

	private final ServiceConnection mServConn = new PaprikaServiceConnection();
	private final PaprikaBroadcastReceiver mReceiver = new PaprikaBroadcastReceiver();
	private IXmppFacade mXmppFacade;
	private UserInfo mUserInfo;
	private SharedPreferences mSettings;
	private boolean mBinded;

	TextView mName;
	TextView mStatus;
	TextView mSignature;
	ImageView mAvatar;

	/*
	 * private static final Uri MY_AVATAR_URI = Uri
	 * .parse(AvatarProvider.CONTENT_URI + "/my_avatar");
	 */

	protected static final int NEED_UPDATE = 1;

	private ViewPager mPager;
	private List<View> listViews;
	private ImageView cursor;
	private TextView t1, t2, t3;
	private int offset = 0;
	private int currIndex = 0;
	private int bmpW;
	private LocalActivityManager manager = null;
	private final Context context = this;
	private TabHost mTabHost;

	/**
	 * Callback for menu creation.
	 * 
	 * @param menu
	 *            the menu created
	 * @return true on success, false otherwise
	 */
	@Override
	public final boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.home_menu, menu);
		return true;
	}

	@Override
	public final boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.home_menu_settings:
			startActivity(new Intent(HomeActivity.this, SettingsActivity.class));
			return true;
		case R.id.home_menu_add_contact:
			startActivity(new Intent(HomeActivity.this,
					AddContactActivity.class));
			return true;
		case R.id.home_menu_disconnect:
			stopService(SERVICE_INTENT);
			Intent intent = new Intent(Intent.ACTION_MAIN);
			intent.addCategory(Intent.CATEGORY_HOME);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
			finish();
			Log.d("######", "home menu disconnect!!!");
			return true;
		default:
			return false;
		}
	}

	@Override
	protected void onCreate(Bundle saveBundle) {
		super.onCreate(saveBundle);
		setContentView(R.layout.home);

		mSettings = PreferenceManager.getDefaultSharedPreferences(this);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		registerReceiver(mReceiver, new IntentFilter(
				PaprikaBroadcastReceiver.Paprika_CONNECTION_CLOSED));

		// requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.home);

		mTabHost = getTabHost();
		mTabHost.addTab(mTabHost.newTabSpec("ContactList").setIndicator("")
				.setContent(new Intent(this, ContactListActivity.class)));
		mTabHost.addTab(mTabHost.newTabSpec("RoomList").setIndicator("")
				.setContent(new Intent(this, RoomListActivity.class)));
		mTabHost.addTab(mTabHost.newTabSpec("ChatList").setIndicator("")
				.setContent(new Intent(this, SessionListActivity.class)));
		mTabHost.setCurrentTab(1);

		manager = new LocalActivityManager(this, true);
		manager.dispatchCreate(saveBundle);

		InitImageView();
		InitTextView();
		InitViewPager();
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (!mBinded)
			mBinded = bindService(SERVICE_INTENT, mServConn, BIND_AUTO_CREATE);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected void onPause() {
		super.onPause();
		if (mBinded) {
			unbindService(mServConn);
			mBinded = false;
		}
		mXmppFacade = null;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mReceiver);
		Log.e(TAG, "onDestroy activity");
	}

	private Bitmap getAvatarBmp() {
		Bitmap bmp;
		String fName = mUserInfo.getJid();
		String filePath = Environment.getExternalStorageDirectory()
				+ "/Android/data/personal.jinhui.paprika/cache/avatar/" + fName;
		File f = new File(filePath);
		if (f.exists()) {
			bmp = BitmapFactory.decodeFile(filePath);
		} else {
			bmp = BitmapFactory.decodeResource(getResources(),
					R.drawable.default_man);
		}

		return ImageHelper.getRoundedCornerBitmap(bmp, 5);
	}

	private int getStatus() {
		int status = mSettings.getInt(PaprikaApplication.STATUS_KEY, 0);
		return status;
	}

	private String getStatusMessage() {
		SharedPreferences pref = PreferenceManager
				.getDefaultSharedPreferences(this);
		String statusMessage = pref.getString(
				PaprikaApplication.STATUS_TEXT_KEY, "");
		return statusMessage;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// Ignore failed requests
		if (resultCode == RESULT_OK) {
			if (requestCode == NEED_UPDATE) {
			}
		}
	}

	private void InitTextView() {
		t1 = (TextView) findViewById(R.id.text1);
		t2 = (TextView) findViewById(R.id.text2);
		t3 = (TextView) findViewById(R.id.text3);

		t1.setOnClickListener(new MyOnClickListener(0));
		t2.setOnClickListener(new MyOnClickListener(1));
		t3.setOnClickListener(new MyOnClickListener(2));
	}

	private void InitViewPager() {
		mPager = (ViewPager) findViewById(R.id.vPager);
		listViews = new ArrayList<View>();
		MyPagerAdapter mpAdapter = new MyPagerAdapter(listViews);
		Intent intent = new Intent(context, ContactListActivity.class);
		listViews.add(getView("Black", intent));
		Intent intent2 = new Intent(context, RoomListActivity.class);
		listViews.add(getView("Gray", intent2));
		Intent intent3 = new Intent(context, SessionListActivity.class);
		listViews.add(getView("White", intent3));
		mPager.setAdapter(mpAdapter);
		mPager.setCurrentItem(0);
		mPager.setOnPageChangeListener(new MyOnPageChangeListener());
	}

	private void InitImageView() {
		cursor = (ImageView) findViewById(R.id.cursor);
		bmpW = BitmapFactory.decodeResource(getResources(), R.drawable.a)
				.getWidth();
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		int screenW = dm.widthPixels;
		offset = (screenW / 3 - bmpW) / 2;
		Matrix matrix = new Matrix();
		matrix.postTranslate(offset, 0);
		cursor.setImageMatrix(matrix);
	}

	public class MyPagerAdapter extends PagerAdapter {
		public List<View> mListViews;

		public MyPagerAdapter(List<View> mListViews) {
			this.mListViews = mListViews;
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView(mListViews.get(arg1));
		}

		@Override
		public void finishUpdate(View arg0) {
		}

		@Override
		public int getCount() {
			return mListViews.size();
		}

		@Override
		public Object instantiateItem(View arg0, int arg1) {
			((ViewPager) arg0).addView(mListViews.get(arg1), 0);
			return mListViews.get(arg1);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == (arg1);
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {
		}
	}

	public class MyOnClickListener implements View.OnClickListener {
		private int index = 0;

		public MyOnClickListener(int i) {
			index = i;
		}

		@Override
		public void onClick(View v) {
			mPager.setCurrentItem(index);
		}
	};

	public class MyOnPageChangeListener implements OnPageChangeListener {

		int one = offset * 2 + bmpW;
		int two = one * 2;

		@Override
		public void onPageSelected(int arg0) {
			Animation animation = null;
			Intent intent = new Intent();
			switch (arg0) {
			case 0:

				Log.d(TAG, "---0---");
				mTabHost.setCurrentTab(0);
				if (currIndex == 1) {
					animation = new TranslateAnimation(one, 0, 0, 0);
				} else if (currIndex == 2) {
					animation = new TranslateAnimation(two, 0, 0, 0);
				}
				break;
			case 1:

				Log.d(TAG, "---1---");
				mTabHost.setCurrentTab(1);
				if (currIndex == 0) {
					animation = new TranslateAnimation(offset, one, 0, 0);
				} else if (currIndex == 2) {
					animation = new TranslateAnimation(two, one, 0, 0);
				}
				break;
			case 2:

				Log.d(TAG, "---2---");
				mTabHost.setCurrentTab(2);
				if (currIndex == 0) {
					animation = new TranslateAnimation(offset, two, 0, 0);
				} else if (currIndex == 1) {
					animation = new TranslateAnimation(one, two, 0, 0);
				}
				break;
			}
			currIndex = arg0;
			animation.setFillAfter(true);
			animation.setDuration(300);
			cursor.startAnimation(animation);
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}
	}

	private View getView(String id, Intent intent) {
		return manager.startActivity(id, intent).getDecorView();
	}

	/**
	 * The service connection used to connect to the Paprika service.
	 */
	private class PaprikaServiceConnection implements ServiceConnection {

		/**
		 * Constructor.
		 */
		public PaprikaServiceConnection() {
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mXmppFacade = IXmppFacade.Stub.asInterface(service);
			try {
				mUserInfo = mXmppFacade.getUserInfo();
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			mAvatar = (ImageView) findViewById(R.id.my_avatar);
			mAvatar.setImageBitmap(getAvatarBmp());
			mAvatar.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent i = new Intent(HomeActivity.this,
							ChangeStatusActivity.class);
					startActivityForResult(i, NEED_UPDATE);
				}
			});
			mName = (TextView) findViewById(R.id.my_name);
			mName.setText(mUserInfo.getName());
			mStatus = (TextView) findViewById(R.id.my_status);
			String[] status_types = getResources().getStringArray(R.array.status_types);
			mStatus.setText(status_types[getStatus()]);
			mSignature = (TextView) findViewById(R.id.my_signature);
			mSignature.setText(getStatusMessage());
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			mXmppFacade = null;
			mBinded = false;
		}
	}
}
